﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace weba.Sales
{
    public partial class PurchaseOrderHeaderEditFromNeedMaterial : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (Request.QueryString["NeedMaterialID"] != null)
                {
                    if (mk.IsNumber(Request.QueryString["NeedMaterialID"].ToString()))
                    {
                        //用一个隐藏Label保存传递过来的ID
                        this.lblNeedMaterialID.Text = Request.QueryString["NeedMaterialID"].ToString();
                    }
                    else
                    {
                        mk.Alert("参数错误！");
                    }
                }
                else
                {
                    mk.Alert("参数错误！");
                }


                //设置经办人信息
                Accounts_Users currentUser = mk.l.Accounts_Users.FirstOrDefault();
                this.lblManagerTrueName.Text = currentUser.TrueName;
                this.lblManagerUserName.Text = currentUser.UserName;
                //设置根部门ID
               var bllDept =mk.l.Accounts_Department.ToList();
                this.lblRootDepartmentID.Text = bllDept.Where(h=>h.ClassID==(int.Parse(currentUser.DepartmentID))).FirstOrDefault().RootID.ToString();
                //给日期输入框添加只读属性，不能在属性里直接设置，不然会取不到值
                this.txtDateOrder.Attributes["readonly"] = "true";
                this.txtDateOrder.Date = System.DateTime.Now;
                //显示订单概况
                this.ShowSalesOrderHeaderInfo();
                this.BindManufacturerID();
            }
        }
        private void BindManufacturerID()
        {
        var bll = mk.l.Sales_Manufacturer.ToList();
        var ds = bll.ToList();
            this.ddlManufacturerID.DataSource = ds;
            this.ddlManufacturerID.DataTextField = "ManufacturerName";
            this.ddlManufacturerID.DataValueField = "ManufacturerID";
            this.ddlManufacturerID.DataBind();
            //ListItem li = new ListItem("无", "0");
            //this.ddlManufacturerID.Items.Add(li);
            //this.ddlManufacturerID.Items.FindByValue("0").Selected = true;
        }

        /// <summary>
        /// Shows the sales order header info.显示订单概况
        /// </summary>
        private void ShowSalesOrderHeaderInfo()
        {
           // UART.BLL.Sales.NeedMaterialHeader bllNeedHeader = new UART.BLL.Sales.NeedMaterialHeader();
       Sales_NeedMaterialHeader mNeedHeader = mk.l.Sales_NeedMaterialHeader.Where(h=>h.NeedMaterialID==int.Parse(this.lblNeedMaterialID.Text)).FirstOrDefault();
            if (mNeedHeader != null)
            {
                //判断是否是本店的订单
                if (int.Parse(this.lblRootDepartmentID.Text) == mNeedHeader.RootDepartmentID)
                {
                    //先判断一下是否已经提交 没提交的就别管了
                    if (mNeedHeader.StatusSubmit == "2")
                    {
                        this.lblSalesOrderID.Text = mNeedHeader.SalesOrderID.ToString();
                      var bllOrderHeader =mk.l.Sales_SalesOrderHeader.ToList();
                               Sales_SalesOrderHeader mOrderHeader = bllOrderHeader.Where(h=>h.SalesOrderID==mNeedHeader.SalesOrderID).FirstOrDefault();
                        if (mOrderHeader != null)
                        {
                            //判断是否已经订货，如果未订货，则转到订货单创建页面
                            if (mNeedHeader.StatusPurchaseMaterial == "2")
                            {
                                //判断流程是否已经完成，如果流程已完成，则不显示添加订货单界面
                                if (mOrderHeader.StatusAll == "2")
                                {
                                    this.pnlAdd.Visible = false;
                                    this.pnlAdd.Enabled = false;
                                }
                                this.lblSalesOrderNumber.Text = mOrderHeader.SalesOrderNumber;
                                this.lblNotesOrder.Text = mOrderHeader.NotesOrder;
                        var bllUser = mk.l.Accounts_Users.ToList();
                             Accounts_Users mUser = bllUser.Where(h=>h.UserName==mOrderHeader.Designer).FirstOrDefault();
                                this.lblDesigner.Text = mUser.TrueName;
                                this.lblDateOrder.Text = mNeedHeader.DateOrder.ToString();
                                this.BindNeedMaterialDetail();
                                this.BindPurchaseOrderHeader();
                            }
                            else
                            {
                                Response.Redirect("PurchaseOrderHeaderCreatFromNeedMaterial.aspx?NeedMaterialID=" + this.lblNeedMaterialID.Text, false);
                            }
                        }
                        else
                        {
                           mk.Alert("参数错误！", "NeedMaterialListForPurchaseOrderHeader.aspx");
                        }
                    }
                    else
                    {
                       mk.Alert("此用料单尚未提交！", "NeedMaterialListForPurchaseOrderHeader.aspx");
                    }
                }
                else
                {
                   mk.Alert("只能查看本店的订单！");
                }
            }
            else
            {
               mk.Alert("参数错误！", "NeedMaterialListForPurchaseOrderHeader.aspx");
            }
        }

        /// <summary>
        /// Binds the need material detail.绑定指定订单的用料单明细信息
        /// </summary>
        private void BindNeedMaterialDetail()
        {
var bll = mk.l.Sales_NeedMaterialDetailandSales_Material.ToList();
          var ds = bll.Where(h=>h.NeedMaterialID.ToString()== this.lblNeedMaterialID.Text).ToList();
            this.myGridViewNeedMaterialDetail.DataSource = ds;
            this.myGridViewNeedMaterialDetail.DataBind();
        }

        /// <summary>
        /// Handles the RowDataBound event of the myGridViewNeedMaterialDetail control.显示厂家名称、代码等信息
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void myGridViewNeedMaterialDetail_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //Label lblManufacturerCode = (Label)(e.Row.FindControl("lblManufacturerCode"));
                Label lblManufacturerName = (Label)(e.Row.FindControl("lblManufacturerName"));
              var bllManufacturer = mk.l.Sales_Manufacturer.ToList();
              Sales_Manufacturer mManufacturer = bllManufacturer.Where(h=>h.ManufacturerID==int.Parse(this.myGridViewNeedMaterialDetail.DataKeys[e.Row.RowIndex].Values["ManufacturerID"].ToString())).FirstOrDefault();
                //lblManufacturerCode.Text = mManufacturer.ManufacturerCode;
                lblManufacturerName.Text = mManufacturer.ManufacturerName;
            }
        }

        /// <summary>
        /// Binds the purchase order header.绑定指定用料单的订货单列表
        /// </summary>
        private void BindPurchaseOrderHeader()
        {
        var bll = mk.l.Sales_PurchaseOrderHeader.ToList();
            var ds = bll.Where(h=>h.NeedMaterialID.ToString()==this.lblNeedMaterialID.Text).ToList();
            this.myGridView.DataSource = ds;
            this.myGridView.DataBind();
        }

        /// <summary>
        /// Handles the RowDataBound event of the myGridView control.显示厂家名称代码等信息
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblManufacturerName = (Label)(e.Row.FindControl("lblManufacturerName"));
     var bllManufacturer = mk.l.Sales_Manufacturer.ToList();
              Sales_Manufacturer mManufacturer = bllManufacturer.Where(h=>h.ManufacturerID==int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["ManufacturerID"].ToString())).FirstOrDefault();
                lblManufacturerName.Text = mManufacturer.ManufacturerName;
            }
        }

        /// <summary>
        /// Handles the Click event of the btnAddOrder control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnAddOrder_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                this.lblMsg2.Text = string.Empty;
           var bll =mk.l.Sales_PurchaseOrderHeader.ToList();
          Sales_PurchaseOrderHeader m = new Sales_PurchaseOrderHeader();
                m.DateOrder = Convert.ToDateTime(this.txtDateOrder.Date);
                m.DatePayment = Convert.ToDateTime("9999-1-1");
                m.Manager = this.lblManagerUserName.Text;
                m.ManufacturerID = int.Parse(this.ddlManufacturerID.SelectedValue);
                m.ModifiedDate = System.DateTime.Now;
                m.NeedMaterialID = int.Parse(this.lblNeedMaterialID.Text);
                m.OrderNumber = mk.InputText(this.txtOrderNumber.Text, 30);
                m.SalesOrderID = int.Parse(this.lblSalesOrderID.Text);
                m.StatusArrival = "0";
                m.StatusPayment = "0";
                m.SubTotal = 0;
                m.RootDepartmentID =int.Parse( this.lblRootDepartmentID.Text);
                try
                {
                 //   bll.Add(m);
                    mk.l.Sales_PurchaseOrderHeader.InsertOnSubmit(m);
                    mk.l.SubmitChanges();
                    this.lblMsg2.Text = "添加成功！请确认订货单明细";
                    //绑定订货单概况列表
                    this.BindPurchaseOrderHeader();
                    //把输入框设置为空
                    this.txtOrderNumber.Text = "";
                    //提交事务
                    //ContextUtil.SetComplete();
                }
                catch (Exception ex)
                {
                    //撤销事务
                    //ContextUtil.SetAbort();
                    this.lblMsg2.Text = "添加错误！错误信息：" + ex.Message;
                }
            }
        }

        /// <summary>
        /// Handles the ServerValidate event of the CustomValidator1 control.判断是否至少添加了一个订货单
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (this.myGridView.Rows.Count > 0)
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }

        /// <summary>
        /// Handles the RowDeleting event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewDeleteEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            this.lblMsg2.Text = string.Empty;
          //  UART.BLL.Sales.PurchaseOrderHeader bll =mk.l
            try
            {
                Sales_PurchaseOrderHeader bla = mk.l.Sales_PurchaseOrderHeader.Where(h => h.RootDepartmentID.ToString() == this.myGridView.DataKeys[e.RowIndex].Values["PurchaseOrderID"].ToString()).FirstOrDefault();
               // bll.Delete(int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["PurchaseOrderID"].ToString()));
              mk.l.Sales_PurchaseOrderHeader.DeleteOnSubmit(bla);
                this.BindPurchaseOrderHeader();
                //提交事务
               // ContextUtil.SetComplete();
            }
            catch
            {
                //撤销事务
                //ContextUtil.SetAbort();
                this.lblMsg2.Text = "删除失败！";
            }
        }

        /// <summary>
        /// Handles the Click event of the btnOK control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                mk.Alert("修改订货单成功！将返回到订货单列表", "PurchaseOrderHeaderList.aspx");
            }
        }
    }
}